package cn.cas.mango.util.paramCheck;

import cn.cas.mango.dto.param.hot.HotSpotParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HotSpotParamCheckUtil {
  public static Map<String, Object> checkParam(HotSpotParam formData, int pageSize) {
    Map<String, Object> map = new HashMap<>();
    String isSuccess = HotSpotParamCheckUtil.checkParam(formData);

    if (!isSuccess.equals("ok")) {
      map.put("isSuccess", isSuccess);
      return map;
    }

    if (Strings.isBlank(formData.getNm()))
      throw new IllegalStateException("nm 不可以为空");

    // pageSize  TODO 配置中的pagesize为30，需求文档中默认值为400，这个之后再确认下
    if (formData.getPageSize() == null || formData.getPageSize() < 0)
      formData.setPageSize(pageSize);

    if (formData.getEntityWeight() == null) {
      formData.setEntityWeight(0.0);
    }

    if (formData.getSimWeight() == null) {
      formData.setSimWeight(0.2);
    }

    if (!Strings.isBlank(formData.getSsly())) {
      String area = formData.getSsly();
      int num;
      try {
        num = Integer.parseInt(area);
        if (num < 2 || num > 20) {
          formData.setSsly(null);
        } else {
          formData.setSsly(String.format("%04d", num));
        }
      } catch (NumberFormatException e) {
        formData.setSsly(null);
      }
    }



    if (Strings.isBlank(formData.getQuery()))
      formData.setQuery("");

    if (Strings.isBlank(formData.getFlags()))
      formData.setFlags("false");

    log.info("Request param:{}", formData);
    map.put("isSuccess", isSuccess);
    map.put("formData", formData);
    return map;

  }

  /**
   * 对共有的参数做检验，currentPage，startDate，endDate
   * 对可填多个值的字段值进行处理
   */
  public static String checkParam(HotSpotParam formData) {
    String isSuccess = "ok";
    if (formData.getCurrentPage() == null || formData.getCurrentPage() <= 0) {
      formData.setCurrentPage(1);
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {
      if (Strings.isNotBlank(formData.getEndDate())) {
        formData.setEndDate(sdf.format(sdf.parse(formData.getEndDate())));
      }
      if (Strings.isNotBlank(formData.getStartDate())) {
        formData.setStartDate(sdf.format(sdf.parse(formData.getStartDate())));
      }
    } catch (Exception e) {
      String info = "参数[endDate或startDate]非法，格式应为'yyyy-MM-dd'";
      log.info(info);
      isSuccess = info;
      return isSuccess;
    }

//    if (Strings.isBlank(formData.getStartDate()) && Strings.isBlank(formData.getEndDate())) {
//
//    }

    // province可为空，多个值使用逗号隔开
    if (Strings.isNotBlank(formData.getProvince()) && !formData.getProvince().equals("全部")) {
      formData.setProvinceArray(ParamCheckUtil.string2FieldValue(formData.getProvince()));
    } else {
      formData.setProvinceArray(new ArrayList<>());
    }

    return isSuccess;
  }
}
